<template>
  <dv-border-box-1 style="height:100%">
    <div id="border">
      <!-- 表单 -->
      <el-form :inline="true" width="100%" :model="searchMap" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="searchMap.content" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item label="热门评论" prop="ishot">
          <el-tooltip :content="searchMap.ishot === '1' ? '热门' : '否'" placement="top">
            <el-switch
              v-model="searchMap.ishot"
              active-color="#13ce66"
              inactive-color="grey"
              active-value="1"
              inactive-value="0"
              @change="handleHotStateChange"
            ></el-switch>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="评论状态" prop="state">
          <el-select size="small" width="50" v-model="searchMap.state" placeholder="请选择">
            <el-option
              v-for="item in StateOptionsOfSearch"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="fetchData">查询</el-button>
        </el-form-item>
        <el-button style="float:right" icon="el-icon-plus" type="primary" circle @click="handleAdd"></el-button>
      </el-form>
      <el-row :gutter="20">
        <el-col :span="24">
          <div>
            <!-- Table -->
            <el-table
              size="mini"
              :data="list"
              border
              row-key="_id"
              lazy
              :load="findChildrens"
              :tree-props="{hasChildren: 'parentid'}"
              style="width: 100%"
              height="460"
            >
              <el-table-column type="index" label="序号" width="50"></el-table-column>
              <el-table-column prop="_id" label="评论id" width="170"></el-table-column>
              <el-table-column prop="articleid" label="文章id" width="100"></el-table-column>
              <el-table-column prop="content" label="内容" width="160"></el-table-column>
              <el-table-column prop="state" label="状态" width="80">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.state === '1' ? '' : 'info'">
                    {{
                    scope.row.state | stateTypeFilter
                    }}
                  </el-tag>
                </template>
              </el-table-column>

              <el-table-column prop="createtime" label="发表时间" width="120">
                <template slot-scope="scope">
                  {{
                  scope.row.createtime | dateFilter
                  }}
                </template>
              </el-table-column>
              <el-table-column prop="username" label="评论人" width="100"></el-table-column>

              <el-table-column prop="replynum" label="回复数" width="50"></el-table-column>
              <el-table-column prop="thumbup" label="点赞数" width="50"></el-table-column>

              <el-table-column
                style="text-align:center;line-herght:100%;display:table-cell"
                label="操作"
                fixed="right"
                width="210px"
              >
                <template slot-scope="scope">
                  <el-popover
                    style="background-color:black"
                    trigger="hover"
                    placement="left"
                    width="40px"
                  >
                    <el-row :gutter="15">
                      <el-col :span="12">
                        <el-button
                          style="margin-left:0px;margin-top:2px"
                          size="mini"
                          type="primary"
                          round
                          @click="handleDetail(scope.row._id, scope.row.parentid)"
                        >查看</el-button>
                      </el-col>
                      <el-col :span="12">
                        <el-button
                          style="float:left"
                          size="mini"
                          type="danger"
                          round
                          @click="handleDisable(scope.row._id)"
                        >禁用</el-button>
                      </el-col>
                    </el-row>
                    <el-button type="primary" size="mini" plain slot="reference">编辑</el-button>
                  </el-popover>
                  <el-button
                    style="margin-left:5px"
                    type="success"
                    @click="
                            handleReply(
                              scope.row._id,
                              scope.row.articleid,
                              scope.row.username,
                              scope.row.targetid
                            )
                          "
                    size="mini"
                    plain
                  >回复</el-button>
                  <el-button
                    style="margin-left:5px"
                    type="warning"
                    size="mini"
                    plain
                    @click="handleThubmup(scope.row._id)"
                  >点赞</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="text-align:center">
              <el-button style="margin=0 auto" icon="el-icon-download" @click="loadMore">点击加载更多</el-button>
            </div>
            <!-- 分页 -->
            <!-- <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[5,10, 15, 20]"
              :page-size="pageSize"
              :layout="!isDialog ?  'total, sizes, prev, pager, next, jumper':'prev,pager,next'"
              :total="total"
            ></el-pagination>-->
          </div>
        </el-col>
        <el-col :span="0">
          <!-- 图片 -->

          <!-- 卡片 -->
          <!-- <el-card :body-style="{ padding: '0px' }" style="height:500px">
            <img
              src="https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png"
              class="image"
            />
            <div style="padding: 14px;">
              <span>好吃的汉堡</span>
              <div class="bottom clearfix">
                <time class="time">{{ currentDate }}</time>
                <el-button type="text" class="button">操作按钮</el-button>
              </div>
            </div>
          </el-card>-->
          <!-- <el-backtop target=".page-component__scroll .el-scrollbar__wrap"></el-backtop> -->
        </el-col>
      </el-row>

      <!-- 抽屉 -->
      <el-drawer
        title="评论信息"
        size="40%"
        style="height:100%"
        :visible.sync="drawer"
        :direction="direction"
      >
        <el-card class="box-card" style="overflow-y:auto;height:85%" shadow="hover">
          <el-collapse v-model="activeName" accordion>
            <el-collapse-item v-if="parentidNull==false" title="父级评论" name="1">
              <el-form
                :model="pojoParent"
                ref="pojoParentForm"
                :rules="rules"
                label-position="right"
                label-width="80px"
                size="mini"
              >
                <el-form-item label="所属文章编号" prop="articleid">
                  <el-input readonly width="60px" v-model="pojoParent.articleid" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="内容" prop="content">
                  <el-input
                    readonly
                    type="textarea"
                    width="60px"
                    v-model="pojoParent.content"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>
                <el-form-item label="状态" prop="state">
                  <el-tooltip :content="pojoParent.state === '1' ? '开启' : '关闭'" placement="top">
                    <el-switch
                      disabled
                      v-model="pojoParent.state"
                      active-color="#13ce66"
                      inactive-color="#ff4949"
                      active-value="1"
                      inactive-value="0"
                    ></el-switch>
                  </el-tooltip>
                </el-form-item>
                <el-form-item label="发表时间" prop="createtime">
                  <el-date-picker
                    readonly
                    v-model="pojoParent.createtime"
                    type="date"
                    placeholder="选择日期"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item label="评论者" prop="username">
                  <el-input readonly width="60px" v-model="pojoParent.username" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="上级评论编号" prop="parentid">
                  <el-input readonly width="60px" v-model="pojoParent.parentid" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="回复数" prop="replynum">
                  <el-input readonly width="60px" v-model="pojoParent.replynum" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="点赞数" prop="thumbup">
                  <el-input readonly width="60px" v-model="pojoParent.thumbup" autocomplete="off"></el-input>
                </el-form-item>
              </el-form>
            </el-collapse-item>

            <el-collapse-item title="当前评论" name="2">
              <el-form
                :model="pojo"
                ref="pojoCurrentForm"
                :rules="rules"
                label-position="right"
                label-width="80px"
                size="mini"
              >
                <el-form-item label="所属文章编号" prop="articleid">
                  <el-input readonly width="60px" v-model="pojo.articleid" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="内容" prop="content">
                  <el-input type="textarea" width="60px" v-model="pojo.content" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="状态" prop="state">
                  <el-tooltip :content="pojo.state === '1' ? '开启' : '关闭'" placement="top">
                    <el-switch
                      disabled
                      v-model="pojo.state"
                      active-color="#13ce66"
                      inactive-color="#ff4949"
                      active-value="1"
                      inactive-value="0"
                    ></el-switch>
                  </el-tooltip>
                </el-form-item>
                <el-form-item label="发表时间" prop="createtime">
                  <el-date-picker readonly v-model="pojo.createtime" type="date" placeholder="选择日期"></el-date-picker>
                </el-form-item>
                <el-form-item label="评论者" prop="username">
                  <el-input readonly width="60px" v-model="pojo.username" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="上级评论编号" prop="parentid">
                  <el-input readonly width="60px" v-model="pojo.parentid" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="回复数" prop="replynum">
                  <el-input readonly width="60px" v-model="pojo.replynum" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="点赞数" prop="thumbup">
                  <el-input readonly width="60px" v-model="pojo.thumbup" autocomplete="off"></el-input>
                </el-form-item>
              </el-form>
              <div class="dialog-footer">
                <el-button @click="drawer = false">取 消</el-button>
                <el-button type="primary" @click="disabledComment">禁用并发送通知</el-button>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-card>
      </el-drawer>

      <!-- 回复窗口 -->
      <el-dialog title="回复评论" :visible.sync="dialogFormVisible">
        <el-form :model="pojoReply" ref="replyForm" :rules="replyRules">
          <el-form-item label="所属文章" label-width="80px">
            <el-input v-model="articleTile" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="回复对象" label-width="80px">
            <el-input v-model="TargerUsername" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label-width="80px" prop="content">
            <el-input
              type="textarea"
              v-model="pojoReply.content"
              placeholder="回复内容"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="replyComment">回 复</el-button>
        </div>
      </el-dialog>
    </div>
  </dv-border-box-1>
</template>
<script>
import moment from "moment"
import commentApi from "@/api/comment.js";
import articleApi from "@/api/article.js";
const stateOptions = [
  { state: "1", statename: "开启" },
  { state: "0", statename: "关闭" }
];
export default {
  data() {
    return {
      parentidNull: false, //父id是否等于0
      StateOptionsOfSearch: [
        {
          value: "1",
          label: "正常"
        },
        {
          value: "0",
          label: "异常"
        }
      ],
      activeName: "",
      direction: "rtl",
      drawer: false,
      list: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchMap: {
        content: "",
        ishot: "",
        state: "1"
      },
      pojoParent: {
        _id: "",
        articleid: "",
        content: "",
        createtime: "",
        state: "",
        userid: "",
        username: "",
        parentid: "",
        replynum: 0,
        thumbup: 0
      },
      pojo: {
        articleid: "",
        content: "",
        state: "",
        createtime: "",
        username: "",
        parentid: "",
        replynum: 0,
        thumbup: 0
      },
      articleTile: "", //回评论中显示文章标题
      TargerUsername: "", //回复评论中显示的目标用户名
      pojoReply: {
        //回复实体
        articleid: "",
        content: "",
        username: "",
        parentid: "",
        targetid:""
      },
      replyRules: {
        //回复表单校验
        content: [
          { required: true, message: "分类名称不能为空", trigger: "blur" }
        ]
      },
      rules: {},
      dialogFormVisible: false
    };
  },
  watch: {
    "searchMap.content": {
      handler(newValue, oldValue) {
        if (newValue !== "" && newValue !== null) {
          this.searchMap.ishot = "0";
        }
      },
      deep: true
    }
  },
  created() {
    this.fetchData();
  },
  methods: {
    loadMore() {
      this.currentPage++;
      commentApi
        .searchPage(this.currentPage, this.pageSize, this.searchMap)
        .then(resp => {
          const respData = resp.data;
          if (respData.flag) {
            this.list = this.list.concat(respData.data.rows);
            this.total = this.total + respData.data.total;
          } else {
            this.$message({
              message: respData.message,
              type: "warning"
            });
            this.currentPage--;
          }
        });
    },
    fetchData() {
      commentApi
        .searchPage(this.currentPage, this.pageSize, this.searchMap)
        .then(resp => {
          const respData = resp.data;
          if (respData.flag) {
            this.list = respData.data.rows;
            this.total = respData.data.total;
          } else {
            this.$message({
              message: respData.message,
              type: "warning"
            });
          }
        });
    },
    handleAdd() {},
    /**
     * 根据id获得子评论
     */
    findChildrens(tree, treeNode, resolve) {
      console.log(tree._id);
      commentApi.findChildrensById(tree._id).then(resp => {
        resolve(resp.data.data);
      });
    },
    /**
     * 查看评论详情，回显数据
     */
    handleDetail(id, parentid) {
      this.drawer = true;
      this.$nextTick(() => {
        this.$refs["pojoCurrentForm"].resetFields();
        if (parentid !== "0") {
          this.$refs["pojoParentForm"].resetFields();
        }
      });
      console.log(parentid);
      if (parentid !== "0") {
        commentApi.getByParentId(parentid).then(respParent => {
          const parentData = respParent.data;
          if (parentData.flag) {
            this.pojoParent = parentData.data;
          } else {
            this.$message({
              type: "warning",
              message: parentData.message
            });
          }
        });
      } else {
        this.parentidNull = true;
      }

      commentApi.getById(id).then(respCurrent => {
        const currentData = respCurrent.data;
        if (currentData.flag) {
          this.pojo = currentData.data;
        } else {
          this.$message({
            message: currentData.message,
            type: "warning"
          });
        }
      });
      // axios
      //   .all([commentApi.getByParentId(parentid), commentApi.getById(id)])
      //   .then(
      //     axios.spread(function(parentResp, currentResp) {
      //       //父级评论返回数据
      //       const parentData = parentResp.data;
      //       //当前评论返回数据
      //       const currentData = currentResp.data;
      //       if (parentResp.data.flag) {
      //         this.pojoParent = parentResp.data.data;
      //       } else {
      //         this.$message({
      //           type: "warning",
      //           message: parentResp.data.message
      //         });
      //       }
      //       if (currentResp.data.flag) {
      //         this.pojo = currentResp.data.data;
      //       } else {
      //         this.$message({
      //           message: currentResp.data.message,
      //           type: "warning"
      //         });
      //       }
      //     })
      //   );
    },
    handleDelete(id) {},
    addData(formName) {},
    /**
     * 搜索区是否热门
     */
    handleHotStateChange(val) {
      if (val !== "0") {
        this.searchMap.content = "";
      }
      this.searchMap.ishot = val;
    },
    /**
     * 点赞
     */
    handleThubmup(id) {
      commentApi.thumbup(id).then(resp => {
        if (resp.data.flag) {
          this.$message({
            type: "success",
            message: resp.data.message
          });
          this.fetchData();
        }
      });
    },
    /**
     * 禁用
     */
    handleDisable(id) {
      this.$confirm("确定关闭此评论吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          commentApi.disableComment(id).then(resp => {
            this.$message({
              type: resp.data.flag ? "success" : "error",
              message: "禁用成功!"
            });
            if (resp.data.flag) {
              this.fetchData();
            }
          });
        })
        .catch(() => {
          return;
        });
    },
    /**
     * 禁用并发送通知
     */
    disabledComment() {
      this.disabledComment();
    },
    /**
     * 搜索区评论状态
     */
    handleSearchStateChange(val) {
      /* if (val !== "0") {
        this.searchMap.content = "";
      }*/
      this.searchMap.state = val;
    },
    /* handleIsNewChange(val) {
      if (val !== "0") {
        this.searchMap.content = "";
      }
      this.searchMap.state = val;
    },*/
    /**
     * 当前评论表单状态改变
     */
    handlePojoFormState(val) {
      this.pojoParent.state = val;
    },
    /**
     * 打开回复窗口
     */
    handleReply(id, articleid, username,targetid) {
      this.dialogFormVisible = true;

      this.$nextTick(() => {
        this.$refs["replyForm"].resetFields();
      });
      articleApi.findArticleById(articleid).then(resp => {
        if (resp.data.flag) {
          this.articleTile = resp.data.data.article.title;
        }
      });
      this.pojoReply.parentid = id;
      this.pojoReply.articleid = articleid;
      this.pojoReply.targetid=targetid;
      this.TargerUsername = username;
    },
    /**
     * 回复
     */
    replyComment() {
      //使用moment转化日期格式

      commentApi.reply(this.pojoReply).then(resp => {
        if (resp.data.flag) {
          this.$message({
            type: "success",
            message: resp.data.message
          });
          this.fetchData();
          this.dialogFormVisible = false;
        } else {
          this.$message({
            type: "warning",
            message: resp.data.message
          });
        }
      });
    }
  },
  filters: {
    stateTypeFilter(type) {
      const stateobj = stateOptions.find(obj => {
        return obj.state === type;
      });
      return stateobj ? stateobj.statename : null;
    },
    dateFilter(input, formatString = "YYYY-MM-DD HH:mm:ss") {
      return moment(input).format(formatString);
    }
  }
};
</script>
<style scoped>
#border {
  padding: 20px;
}
</style>
